package com.api.sw.duban.util;

import java.io.*;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ibm.icu.text.SimpleDateFormat;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import weaver.general.Util;


/**
 * @Description 导出word文档
 * @Author  Huangxiaocong
 * 2018年12月1日  下午12:12:15
 */
public class ExportWord {
    private XWPFHelperTable xwpfHelperTable = null;
    private XWPFHelper xwpfHelper = null;
    public ExportWord() {
        xwpfHelperTable = new XWPFHelperTable();
        xwpfHelper = new XWPFHelper();
    }
    /**
     * 创建好文档的基本 标题，表格  段落等部分
     * @return
     * @Author Huangxiaocong 2018年12月16日
     */
    public XWPFDocument createXWPFDocument() {
        XWPFDocument doc = new XWPFDocument();

        createTitleParagraph(doc);
        createTableParagraph(doc, 10, 6);
        return doc;
    }
    public XWPFDocument createXWPFDocument(int row,int col) {
        XWPFDocument doc = new XWPFDocument();
        CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
        //ooxml-schemas 1.1
        CTPageSz cTPageMar=sectPr.addNewPgSz();
        cTPageMar.setW(BigInteger.valueOf(26002));
        cTPageMar.setH(BigInteger.valueOf(16840));
        cTPageMar.setOrient(STPageOrientation.LANDSCAPE);

        createTitleParagraphTime(doc);
        createTableParagraph(doc, row, col);
        return doc;
    }
    /**
     * 创建表格的标题样式
     * @param document
     * @Author Huangxiaocong 2018年12月16日 下午5:28:38
     */
    public void createTitleParagraph(XWPFDocument document) {
        XWPFParagraph titleParagraph = document.createParagraph();    //新建一个标题段落对象（就是一段文字）
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);//样式居中
        XWPFRun titleFun = titleParagraph.createRun();    //创建文本对象
//        titleFun.setText(titleName); //设置标题的名字
        titleFun.setBold(true); //加粗
        titleFun.setColor("000000");//设置颜色
        titleFun.setFontSize(25);    //字体大小
//        titleFun.setFontFamily("");//设置字体
        //...
        titleFun.addBreak();    //换行
    }
    /**
     * 创建表格的标题样式  以及制表日期时间
     * @param document
     * @Author Huangxiaocong 2018年12月16日 下午5:28:38
     */
    public void createTitleParagraphTime(XWPFDocument document) {
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        XWPFParagraph titleParagraph = document.createParagraph();    //新建一个标题段落对象（就是一段文字）
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);//样式居中
        XWPFRun titleFun = titleParagraph.createRun();    //创建文本对象
//        titleFun.setText(titleName); //设置标题的名字
        titleFun.setBold(true); //加粗
        titleFun.setColor("000000");//设置颜色
        titleFun.setFontSize(25);    //字体大小
//        titleFun.setFontFamily("");//设置字体
        //...
        titleFun.addBreak();    //换行
        //设置制单的时间
        XWPFParagraph titleParagraphTime = document.createParagraph();
        titleParagraphTime.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun titleFunTime=titleParagraphTime.createRun();
        titleFunTime.setText("制单日期"+sim.format(new Date()));
        titleFunTime.addBreak();//换行
    }
    /**
     * 设置表格
     * @param document
     * @param rows
     * @param cols
     * @Author Huangxiaocong 2018年12月16日
     */
    public void createTableParagraph(XWPFDocument document, int rows, int cols) {
//        xwpfHelperTable.createTable(xdoc, rowSize, cellSize, isSetColWidth, colWidths)
        XWPFTable infoTable = document.createTable(rows, cols);
        xwpfHelperTable.setTableWidthAndHAlign(infoTable, "9072", STJc.CENTER);
        //合并表格  不需要合并

        //xwpfHelperTable.mergeCellsHorizontal(infoTable, 1, 1, 5);
        //xwpfHelperTable.mergeCellsVertically(infoTable, 0, 3, 6);
        //for(int col = 3; col < 7; col++) {
            //xwpfHelperTable.mergeCellsHorizontal(infoTable, col, 1, 5);
        //}
        //设置表格样式
        List<XWPFTableRow> rowList = infoTable.getRows();
        for(int i = 0; i < rowList.size(); i++) {
            XWPFTableRow infoTableRow = rowList.get(i);
            List<XWPFTableCell> cellList = infoTableRow.getTableCells();
            for(int j = 0; j < cellList.size(); j++) {
                XWPFParagraph cellParagraph = cellList.get(j).getParagraphArray(0);
                cellParagraph.setAlignment(ParagraphAlignment.CENTER);
                XWPFRun cellParagraphRun = cellParagraph.createRun();
                cellParagraphRun.setFontSize(12);
                if(i % 2 != 0) {
                    //cellParagraphRun.setBold(true);
                }
            }
        }
        xwpfHelperTable.setTableHeight(infoTable, 560, STVerticalJc.CENTER);
    }

    /**
     * 往表格中填充数据
     * @param dataList
     * @param document
     * @throws IOException
     * @Author Huangxiaocong 2018年12月16日
     */
    //, OutputStream os
    @SuppressWarnings("unchecked")
    public void exportCheckWord(Map<String, Object> dataList, XWPFDocument document, String savePath) throws IOException {
        XWPFParagraph paragraph = document.getParagraphArray(0);
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleFun = (XWPFRun) paragraph.getRuns().get(0);
        titleFun.setText(String.valueOf(dataList.get("TITLE")));
        titleFun.addBreak();
        List<List<Object>> tableData = (List<List<Object>>) dataList.get("TABLEDATA");
        XWPFTable table = document.getTableArray(0);

        fillTableDataByXWPFDocument(table, tableData,document);
        xwpfHelper.saveDocument(document, savePath);
    }
    public void exportCheckWordOut(Map<String, Object> dataList, XWPFDocument document, OutputStream os) throws IOException {
        XWPFParagraph paragraph = document.getParagraphArray(0);
        XWPFRun titleFun = (XWPFRun) paragraph.getRuns().get(0);
        titleFun.setText(String.valueOf(dataList.get("TITLE")));
        List<List<Object>> tableData = (List<List<Object>>) dataList.get("TABLEDATA");
        XWPFTable table = document.getTableArray(0);
        fillTableDataByXWPFDocument(table, tableData,document);
        xwpfHelper.saveDocument(document, "D:/expWordTest9.docx");
        xwpfHelper.saveDocument(document, os);
        //SreamConvenout(os);
    }
    public void exportCheckWordOut1(Map<String, Object> dataList, XWPFDocument document) throws IOException {
        XWPFParagraph paragraph = document.getParagraphArray(0);
        XWPFRun titleFun = (XWPFRun) paragraph.getRuns().get(0);
        titleFun.setText(String.valueOf(dataList.get("TITLE")));
        List<List<Object>> tableData = (List<List<Object>>) dataList.get("TABLEDATA");
        XWPFTable table = document.getTableArray(0);
        //fillTableData(table, tableData);
        fillTableDataByXWPFDocument(table, tableData,document);
    }
    /**
     * 往表格中填充数据
     * @param table
     * @param tableData
     * @Author Huangxiaocong 2018年12月16日
     */
    public void fillTableData(XWPFTable table, List<List<Object>> tableData) {
        List<XWPFTableRow> rowList = table.getRows();
        for(int i = 0; i < tableData.size(); i++) {
            List<Object> list = tableData.get(i);
            List<XWPFTableCell> cellList = rowList.get(i).getTableCells();
            for(int j = 0; j < list.size(); j++) {
                System.out.println(cellList.get(j).getParagraphs().size());
                XWPFParagraph cellParagraph = cellList.get(j).getParagraphArray(0);
                cellParagraph.setAlignment(ParagraphAlignment.CENTER);// llf 新增内容居中
                XWPFRun cellParagraphRun = (XWPFRun) cellParagraph.getRuns().get(0);

                cellParagraphRun.setText(String.valueOf(list.get(j)));
                cellParagraphRun.addBreak();// llf 换行
                //如果存在 /n需要 这只换行




            }
        }
    }
    public void fillTableDataByXWPFDocument(XWPFTable table, List<List<Object>> tableData,XWPFDocument XWPFDocument) {
        List<XWPFTableRow> rowList = table.getRows();
        for(int i = 0; i < tableData.size(); i++) {
            List<Object> list = tableData.get(i);
            List<XWPFTableCell> cellList = rowList.get(i).getTableCells();
            for(int j = 0; j < list.size(); j++) {
                String cellvalue=String.valueOf(list.get(j));
                XWPFParagraph cellParagraph = cellList.get(j).getParagraphArray(0);
                if(cellvalue.indexOf("\n")>0){//
                    //分段
                   String[]  cellvalues=cellvalue.split("\n");
                   for(int celi=0;celi<cellvalues.length;celi++){
                       String cellvaluesDemo= Util.null2String(cellvalues[celi]) ;
                        if(!"".equals(cellvaluesDemo)){
                            if(celi==0){
                                if(i==0){
                                    cellParagraph.setAlignment(ParagraphAlignment.CENTER);// llf 新增内容居中
                                }else{
                                    cellParagraph.setAlignment(ParagraphAlignment.LEFT);// llf 新增内容居中
                                }

                                XWPFRun cellParagraphRun = (XWPFRun) cellParagraph.getRuns().get(0);

                                cellParagraphRun.setText(String.valueOf(cellvaluesDemo));
                                if(celi<(cellvalues.length-1)){
                                    //cellParagraphRun.addBreak();
                                }
                            }else{
                                XmlCursor cursor = cellParagraph .getCTP().newCursor();

                                cellList.get(j).addParagraph();
                                XWPFParagraph newPara =cellList.get(j).getParagraphArray(1);

                                if(i==0){
                                    newPara.setAlignment(ParagraphAlignment.CENTER);// llf 新增内容居中
                                }else{
                                    newPara.setAlignment(ParagraphAlignment.LEFT);// llf 新增内容居中
                                }
                                XWPFRun cellParagraphRun1 = (XWPFRun)  newPara.createRun();//newPara.getRuns().get(0);

                                cellParagraphRun1.setText(cellvaluesDemo);
                                if(celi<(cellvalues.length-1)){
                                    //cellParagraphRun1.addBreak();
                                }
                            }

                        }
                   }
                }else{
                    //XWPFParagraph cellParagraph = cellList.get(j).getParagraphArray(0);
                    if(i==0){
                        cellParagraph.setAlignment(ParagraphAlignment.CENTER);// llf 新增内容居中
                    }else{
                        cellParagraph.setAlignment(ParagraphAlignment.LEFT);// llf 新增内容居中
                    }

                    XWPFRun cellParagraphRun = (XWPFRun) cellParagraph.getRuns().get(0);

                    cellParagraphRun.setText(String.valueOf(list.get(j)));
                }

                //cellParagraphRun.addBreak();// llf 换行
                //如果存在 /n需要 这只换行
                //XmlCursor cursor = cellParagraph .getCTP().newCursor();

                //cellList.get(j).addParagraph();
                //XWPFParagraph newPara =cellList.get(j).getParagraphArray(1);

                //if(i==0){
                    //newPara.setAlignment(ParagraphAlignment.CENTER);// llf 新增内容居中
                //}else{
                    //newPara.setAlignment(ParagraphAlignment.LEFT);// llf 新增内容居中
                //}
                //XWPFRun cellParagraphRun1 = (XWPFRun)  newPara.createRun();//newPara.getRuns().get(0);

                //cellParagraphRun1.setText("1212");
                //cellParagraphRun1.addBreak();// llf 换行



            }
        }
    }
    public void SreamConvenout( OutputStream os){
        File file=new File("D:"+File.separator+"222.docx");
        try{
            InputStream inp=new FileInputStream(file);
            int ch;
            byte[] bs = new byte[10 * 1024];
            while ((ch = inp.read(bs)) != -1) {
                os.write(bs);
            }

        }catch(Exception e){

        }
    }
}